package org.example.springgobang.api;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springgobang.mapper.UserMapper;
import org.example.springgobang.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request) {
        if (username == null || password == null) {
            //返回一个空对象，即返回一个无效对象
            System.out.println("登录失败");
            return new User();
        }
        //根据username去数据库查询，若一致则登录成功
        User user = userMapper.selectByName(username);
        log.info("[login] user="+user);
        if(user==null||!user.getPassword().equals(password)){
            log.info("登录失败");
            return new User();
        }
        log.info("玩家："+user.getUsername()+"登录成功");
        HttpSession session = request.getSession(true);//true：会话存在直接返回，会话不存在，创建一个新的会话
        //保存 session 让后续在访问其他的 api 时也能去获取到用户的信息
        session.setAttribute("user", user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insertUser(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e /*username重复*/) {
            User user = new User();
            return user;
        }
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session==null){
            return new User();
        }
        try {
            //空指针异常
            User tmpUser = (User)session.getAttribute("user");
            User user = userMapper.selectByName(tmpUser.getUsername());
            return user;
        }catch (NullPointerException e) {
            return new User();
        }
    }
}
